﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using YL.NetCore.NetCoreApp;
using IServices;
using SqlSugar;
using YL.Core.Dto;
using YL.Core.Entity.Fluent.Validation;
using YL.Core.Entity;
using YL.Utils.Table;
using YL.Utils.Pub;
using YL.Utils.Extensions;

namespace EduCMS.Controllers
{
    [Route("[controller]")]
    [ApiController]
    public class StudentController : BaseController
    {
        private readonly IWhr_studentServices _studentServices;
        private readonly SqlSugarClient _client;

        public StudentController(SqlSugarClient client,IWhr_studentServices studentServices)
        {
            _client = client;
            _studentServices = studentServices;
        }

        //student/show
        [HttpGet("show")]
        public IActionResult Get([FromForm]Bootstrap.BootstrapParams bootstrap)
        {
            if (bootstrap.limit == 0) 
            {
                bootstrap.limit = 10;
            }
            var sd = _studentServices.PageList(UserDto.UserId, bootstrap);
            return Json(Microprogram.DataInfo(PubEnum.Success, "", new { total = sd.Item1, rows = sd.Item2 }));
        }

        // GET: /student/5
        [HttpGet("{id}", Name = "Get")]
        public JsonResult Get(int id)
        {
            var student = _studentServices.QueryableToEntity(c => c.StudentId == id);
            return Json(Microprogram.DataInfo(PubEnum.Success, "", student));
        }

        //添加信息卡
        // POST: Student
        [HttpPost]
        public IActionResult Post([FromForm]Whr_student student)
        {
            var validator = new StudentFluent();
            var results = validator.Validate(student);
            var success = results.IsValid;
            if (success)
            {
                student.UserId = UserDto.UserId;               
                bool flag = _studentServices.Insert(student);
                return Json(flag ? new { code = PubEnum.Success, msg = PubConst.Add1 } : new { code = PubEnum.Failed, msg = PubConst.Add2 });
            }
            var msg = results.Errors.Aggregate("", (current, item) => current + item.ErrorMessage);
            return Json(Microprogram.DataInfo(PubEnum.Failed, msg, new { }));
        }

        // PUT: Student/5
        [HttpPut("{id}")]
        public IActionResult Put(int id, [FromForm]Whr_student student)
        {
            var entity = _studentServices.QueryableToEntity(s => s.UserId == id);
            if (entity is null) 
            {
                return Json(Microprogram.DataInfo(PubEnum.Failed, "数据有误", new { }));
            }
            var validator = new StudentFluent();
            var results = validator.Validate(student);
            var success = results.IsValid;
            if (success)
            {
                student.UserId = UserDto.UserId;
                student.CreateAt = entity.CreateAt;
                student.UpdateAt = DateTimeExt.DateTime;
                if (student.Age != entity.Age) 
                {
                    student.UpdateAgeAt = DateTimeExt.GetDateTime(DateTimeExt.DateTimeShortFormat);
                }
                bool flag = _studentServices.UpdateEntity(student);
                return Json(flag ? new { code = PubEnum.Success, msg = PubConst.Update1 } : new { code = PubEnum.Failed, msg = PubConst.Update2 });
            }
            var msg = results.Errors.Aggregate("", (current, item) => current + item.ErrorMessage);
            return Json(Microprogram.DataInfo(PubEnum.Failed, msg, new { }));
        }

        // DELETE: api/ApiWithActions/5
        [HttpDelete("{id}")]
        public void Delete(int id)
        {
            Whr_student student = _studentServices.QueryableToEntity(s => s.UserId == id && s.StudentId == id);
            // 信息卡不存在
            if (student is null) 
            {
                return;
            }

            // 是否有申请课程
            int count = _client.Queryable<Whr_course_apply>()
                .Where(a => a.StudentId == student.StudentId)
                .Count();
            if (count > 0)
            {
                return;
            }

            // 删除信息卡
            _studentServices.Delete(student);
        }
    }
}
